package com.lzy.cloud.payment.pay.weixin;


import com.lzy.cloud.payment.utils.StringUtil;

import java.util.*;


public class WxPayData {
	private HashMap<String, Object> hashMap  = new HashMap<String, Object>();


	public void putAll(Map<String,String> map){
		hashMap.putAll(map);
	}
	
	public void put(String key, Object value) {
		hashMap.put(key, value);
	}

	public Object get(String key) {
		return hashMap.get(key)+"";
	}
	
	public boolean isSet(String key){
		return hashMap.containsKey(key);
	}
	
	public String toUrl(){
		if (hashMap.size() == 0)
			return "";
		
		StringBuffer sb = new StringBuffer();
		
		List<String> keys = new ArrayList<String>(hashMap.keySet());
		Collections.sort(keys);

		for(int i = 0;i< keys.size();i++){
			try{
				String key = keys.get(i),val = hashMap.get(key).toString();
				if(!key.equals("sign") && !StringUtil.isNullOrEmpty(val)){
					sb.append("&").append(key).append("=").append(val);
				}
				System.out.println("key--"+key);
			}catch(Exception e){
				System.out.println("------key"+keys.get(i));
			}

		}
		return sb.substring(1);
	}

	@SuppressWarnings("rawtypes")
	public String toXml() {
		if (hashMap.size() == 0)
			return "";

		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");

		Iterator iter = hashMap.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			String key = (String) entry.getKey(), val = (String) entry.getValue();
			if ("attach".equalsIgnoreCase(key) || "body".equalsIgnoreCase(key) || "sign".equalsIgnoreCase(key)) {
				sb.append("<" + key + ">" + "<![CDATA[" + val + "]]></" + key + ">");
			} else {
				sb.append("<" + key + ">" + val + "</" + key + ">");
			}
		}

		sb.append("</xml>");
		return sb.toString();
	}
	
	public String toJson(){
		return StringUtil.toJSON(hashMap);
	}
	public String makeSign(){
		String sign = this.toUrl() + "&key=" + Config.KEY;	
		String md5 = StringUtil.toMD5(sign);		
		return md5.toUpperCase();
	}
	public Map<String,Object> toMap(){
		Map<String, Object> map = hashMap;
		return map;
	}
}
